package com.codingxyz.simple;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;

public class LamdaDemo {

    int[] arr = {4,12,1,3,5,7,9};

    @Test
    public void filter(){
        Arrays.stream(arr).filter((x) -> x%2 !=0).forEach(System.out::println);
    }

    @Test
    public void map(){
        Arrays.stream(arr).map((x) -> x * x).forEach(System.out::println);
    }

    @Test
    public void reduce(){
        Arrays.stream(arr).reduce((x,y) -> x+y).ifPresent(System.out::println);
        System.out.println(Arrays.stream(arr).reduce(-10, (x, y) -> x + y));
    }

    @Test
    public void collect(){
        List<Integer> list = Arrays.stream(arr).collect(ArrayList::new,ArrayList::add,ArrayList::addAll);
        System.out.println(list);

        Set<Integer> set = list.stream().collect(Collectors.toSet());
        System.out.println(set);

    }

    @Test
    public void peek(){
        long count = Arrays.stream(arr).filter(x -> x > 2).peek(System.out::println).count();
        System.out.println(count);
    }

    @Test
    public void average(){
        Arrays.stream(arr).average().ifPresent(System.out::println);
    }

    @Test
    public void sum(){
        System.out.println(Arrays.stream(arr).sum());
    }

    @Test
    public void max(){
        Arrays.stream(arr).max().ifPresent(System.out::println);
    }

    @Test
    public void min(){
        Arrays.stream(arr).min().ifPresent(System.out::println);
    }

    @Test
    public void sorted(){
    }

    @Test
    public void groupBy(){
    }

    @Test
    public void join(){
    }

    @Test
    public void flatMap(){
    }

    @Test
    public void arrStream(){
        Arrays.stream(arr).forEach(System.out::println);
    }

    @Test
    public void then(){
//        IntConsumer out = System.out::println;
//        IntConsumer err = System.err::println;
        IntConsumer out = (x) -> System.out.println("out consume:"+x);
        IntConsumer err = (x) -> System.err.println("err consume:"+x);
//        Arrays.stream(arr).forEach(out.andThen(err));
        Arrays.stream(arr).forEach(err.andThen(out));
    }


    @Test
    public void foreach(){
        List<Integer> numbers = Arrays.asList(1,2,3,4,5,6);
        numbers.forEach(System.out::println);
    }

    @Test
    public void visitOuterVar(){
        final int num = 2;
        Function<Integer,Integer> fun = (from) -> from * num;
        System.out.println(fun.apply(3));
    }
}
